import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookies from 'js-cookie'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login')
  },
  {
    path: '/404',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Error/404'),
  },
  {
    path: '/500',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Error/500')
  },
  
]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const whiteList = ['/login', '/404', '/500']
// 跳转路由 会触发这个钩子
// to : 你要跳哪里
// from : 你从哪里来
// next: 你要不要跳 下一步 通过
router.beforeEach(async (to, from , next) => {
  let token = Cookies.get('token');
  if(whiteList.includes(to.path)) {
    // 不需要权限
    next();
  } else {
    // 需要权限
    // 有没有登陆
    if(token) {
      // 获取到动态路由表
      let routerList = store.state.user.routerList;
      // 获取 权限
      let author = sessionStorage.getItem('author') || '';
      if(routerList.length <= 0 && author) {
        // 在获取一次 动态路由表
        await store.dispatch('user/actionsGetRouterList', author)
        // replace 路由跳转的时候 会替换 历史记录
        next({ ...to, replace: true })
      } else {
        next();
      }
    } else {
      next('/login')
    }
  }
})

export default router
